# -*- coding:utf-8 -*-
import paramiko
import socket
import os,sys
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

#远程执行命令
class remote():

    def __init__(self, server, port, username, password):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(server, port, username, password)

    #执行命令
    def execute(self, shellcmd):
        stdin, stdout, stderr = self.ssh.exec_command(shellcmd)
        self.ssh.close()
        return stdout.readlines()

    #上传文件
    def upload(self,localfile, remotefile):
        remotepath = remotefile
        localpath = localfile
        ret = self.sftp.put(localpath, remotepath)
        self.t.close()
        return ret

    #下载文件
    def download(server, port, username, password, remotefile, localfile):
        remotepath = remotefile
        localpath = localfile
        ret = self.sftp.get(remotepath, localpath)
        self.t.close()
        return ret

def get_now():
    return datetime.now().isoformat()
    

if __name__ == '__main__':
    import config
    import html
    import sendmail
    rows = []
    cols = ['server', 'port', 'username','status', 'check_time']
    for server,port,username,password in config.list:
        try:
            remote_host = remote(server=server, username=username, password=password, port=port)
            del remote_host
            print("SERVER: %s |PORT: %s |USERNAME: %s 登录成功" % (server, port, username))
            rows.append((server,port,username,'登录成功', get_now()))
        except paramiko.ssh_exception.AuthenticationException as e:
            print("SERVER: %s |PORT: %s |USERNAME: %s 认证失败, [%s]: %s" % (server, port, username, str(e.__class__), str(e)))
            rows.append((server,port,username,'登录成功', get_now()))
        except socket.error as e:
            print("SERVER: %s |PORT: %s |USERNAME: %s 连接异常 [%s]: %s" % (server, port, username, str(e.__class__), str(e)))
            rows.append((server,port,username,'连接异常', get_now()))
    

    sub = '登录监控状态'
    page = html.res_html(cols, rows, sub)
    page.printOut('monitor.html')
    content = sendmail.read_content('monitor.html')
    if sendmail.send_mail(config.to_list, sub, content):
        print("[%s] to %s 发送成功." % (sub, config.to_list)) 
    else:
        print("[%s] to %s 发送失败." % (sub, config.to_list)) 
        
